package 回溯;

import java.util.ArrayList;
import java.util.List;

public class _39_组合总和 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> temp = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();

        backtrack(candidates, target, temp, res, 0, 0);
        return res;
    }

    private void backtrack(int[] candidates, int target, List<Integer> temp, List<List<Integer>> res, int cur, int begin) {
        if (cur >= target) {
            if (cur == target) {
                res.add(new ArrayList<>(temp));
            }
            return;
        }

        for (int i = 0; i < candidates.length; i++) {
            temp.add(candidates[i]);
            backtrack(candidates,target,temp,res,cur + candidates[i],i);
            temp.remove(temp.size() - 1);
        }
    }
}
